package cn.sdhuijin.healthexam.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;

public class Util {

	public static final String version = "1.7";

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendHttpGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			// System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendHttpPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			// System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static void update(final Context c, final String url) {
		new Thread() {
			public void run() {
				String ver = Util.sendHttpGet(url + "version.txt", "v="
						+ version);
				if (!ver.trim().equals(version)) {
					Log.e("Util Version", ver);
					Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url
							+ "client-" + ver + ".apk"));
					// it.setClassName("com.android.browser",
					// "com.android.browser.BrowserActivity");
					it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					c.startActivity(it);
				}
			}
		}.start();
	}

	public static void upload(final String ip, final Integer port,
			final String user, final String pass, final String ffile,
			final String tfile) {
		new Thread() {
			public void run() {
				try {
					System.out.println(ffile);
					System.out.println(tfile);
					FTPUtil fu = new FTPUtil();
					fu.connectFTPServer(ip, port, user, pass);
					fu.uploadFile(ffile, tfile);

				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("异常信息：" + e.getMessage());
				}
			}
		}.start();
	}

	/**
	 * 时间转换"yyyyMMddHHmmss"->"yyyy-MM-dd HH:mm:ss"
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDateTime(String date) {
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date dDate = null;
		try {
			dDate = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			System.out.println("异常信息：" + e.getMessage());
		}
		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String reTime = format2.format(dDate);
		return reTime;
	}

	/**
	 * 判断字符串数组中的所有字符串是否为空
	 * 
	 * @param str
	 *            字符串数组
	 * @return 字符串都不为空，返回true；否则，返回false
	 */
	public static boolean allIsNotEmpty(String... str) {
		Boolean flag = true;
		for (String s : str) {
			if (s == null || s.equals("")) {
				flag = false;
			}
		}
		return flag;
	}

	/**
	 * 获取系统时间：yyyyMMddHHmmss
	 * 
	 * @return 系统时间
	 */
	public static String getCurrentDateTime() {
		String time = "";
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyyMMddHHmmss");
			Calendar calendar = Calendar.getInstance();
			time = simpleDateFormat.format(calendar.getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return time;
	}

	public static boolean identifyNumValidateCheck(String identifyNum) {
		boolean validate = false;
		try {
			if (!allIsNotEmpty(identifyNum)) {
				return validate;
			} else {

			}
		} catch (Exception e) {

		}
		return validate;
	}

	/**
	 * 身份证号验证
	 * 
	 * @param IDStr
	 * @return
	 * @throws ParseException
	 */
	public static boolean IDCardValidate(String IDStr) throws ParseException {
		boolean validate = false;
		try {
			String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5",
					"4", "3", "2" };
			String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3",
					"7", "9", "10", "5", "8", "4", "2" };
			String Ai = "";
			// ================ 号码的长度 15位或18位 ================
			if (IDStr.length() != 15 && IDStr.length() != 18) {
				return validate;
			}
			// =======================(end)========================

			// ================ 数字 除最后以为都为数字 ================
			if (IDStr.length() == 18) {
				Ai = IDStr.substring(0, 17);
			} else if (IDStr.length() == 15) {
				Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
			}
			if (isNumeric(Ai) == false) {
				return validate;
			}
			// =======================(end)========================

			// ================ 出生年月是否有效 ================
			String strYear = Ai.substring(6, 10);// 年份
			String strMonth = Ai.substring(10, 12);// 月份
			String strDay = Ai.substring(12, 14);// 月份
			if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
				return validate;
			}
			GregorianCalendar gc = new GregorianCalendar();
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
			if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
					|| (gc.getTime().getTime() - s.parse(
							strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
				return validate;
			}
			if (Integer.parseInt(strMonth) > 12
					|| Integer.parseInt(strMonth) == 0) {
				return validate;
			}
			if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
				return validate;
			}
			// =====================(end)=====================

			// ================ 地区码时候有效 ================
			Hashtable<String, String> h = GetAreaCode();
			if (h.get(Ai.substring(0, 2)) == null) {
				return validate;
			}
			// ==============================================

			// ================ 判断最后一位的值 ================
			int TotalmulAiWi = 0;
			for (int i = 0; i < 17; i++) {
				TotalmulAiWi = TotalmulAiWi
						+ Integer.parseInt(String.valueOf(Ai.charAt(i)))
						* Integer.parseInt(Wi[i]);
			}
			int modValue = TotalmulAiWi % 11;
			String strVerifyCode = ValCodeArr[modValue];
			Ai = Ai + strVerifyCode;

			if (IDStr.length() == 18) {
				if (Ai.equals(IDStr) == false) {
					return validate;
				}
			}
			// =====================(end)=====================
			validate = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return validate;
	}

	/**
	 * 功能：设置地区编码
	 * 
	 * @return Hashtable 对象
	 */
	private static Hashtable<String, String> GetAreaCode() {
		Hashtable<String, String> hashtable = new Hashtable<String, String>();
		hashtable.put("11", "北京");
		hashtable.put("12", "天津");
		hashtable.put("13", "河北");
		hashtable.put("14", "山西");
		hashtable.put("15", "内蒙古");
		hashtable.put("21", "辽宁");
		hashtable.put("22", "吉林");
		hashtable.put("23", "黑龙江");
		hashtable.put("31", "上海");
		hashtable.put("32", "江苏");
		hashtable.put("33", "浙江");
		hashtable.put("34", "安徽");
		hashtable.put("35", "福建");
		hashtable.put("36", "江西");
		hashtable.put("37", "山东");
		hashtable.put("41", "河南");
		hashtable.put("42", "湖北");
		hashtable.put("43", "湖南");
		hashtable.put("44", "广东");
		hashtable.put("45", "广西");
		hashtable.put("46", "海南");
		hashtable.put("50", "重庆");
		hashtable.put("51", "四川");
		hashtable.put("52", "贵州");
		hashtable.put("53", "云南");
		hashtable.put("54", "西藏");
		hashtable.put("61", "陕西");
		hashtable.put("62", "甘肃");
		hashtable.put("63", "青海");
		hashtable.put("64", "宁夏");
		hashtable.put("65", "新疆");
		hashtable.put("71", "台湾");
		hashtable.put("81", "香港");
		hashtable.put("82", "澳门");
		hashtable.put("91", "国外");
		return hashtable;
	}

	/**
	 * 功能：判断字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	private static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (isNum.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 功能：判断字符串是否为日期格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isDate(String strDate) {
		Pattern pattern = Pattern
				.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Matcher m = pattern.matcher(strDate);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 手机号码验证
	 * 
	 * @param number
	 * @return
	 */
	public static boolean isMobileNum(String number) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(number);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 电话号码验证
	 * 
	 * @param number
	 * @return
	 */
	public static boolean isTelphoneNum(String number) {
		Pattern p = Pattern.compile("^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}$");
		Matcher m = p.matcher(number);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 返回格式化日期 YYYY-MM-DD
	 * 
	 * @param date
	 *            待格式化日期
	 * @return YYYY-MM-DD
	 */
	public static String dateFormat(String date) {
		String str = "";
		DateFormat format = null;
		Date dDate = null;
		try {
			if (date.length() == 8) {
				format = new SimpleDateFormat("yyyyMMdd");
				dDate = format.parse(date);
				format = new SimpleDateFormat("yyyy-MM-dd");
				str = format.format(dDate);
			} else if (date.length() == 10) {
				format = new SimpleDateFormat("yyyy-MM-dd");
				dDate = format.parse(date);
				format = new SimpleDateFormat("yyyyMMdd");
				str = format.format(dDate);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 检查网络是否可用
	 * 
	 * @param context
	 * @return	可用返回true,不可用返回false
	 */
	public static boolean isNetAvailable(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		return (info != null && info.isAvailable());
	}
}
